-- Generated from template
require('precache')
if Kekaishi == nil then
	Kekaishi = class({})
	_G.Kekaishi = Kekaishi
end

require('events')
require('utility_functions')
require('testsample')
require('libraries.minHeap')

require "libraries.popmsg"
function Precache( context )
	--[[
		Precache things we know we'll use.  Possible file types include (but not limited to):
			PrecacheResource( "model", "*.vmdl", context )
			PrecacheResource( "soundfile", "*.vsndevts", context )
			PrecacheResource( "particle", "*.vpcf", context )
			PrecacheResource( "particle_folder", "particles/folder", context )
	]]
	PrecacheEveryThingFromKV( context )
end

-- Create the game mode when we activate
function Activate()
	GameRules.AddonTemplate = Kekaishi()
	GameRules.AddonTemplate:InitGameMode()
end
local curDistance = 1800
function Kekaishi:InitGameMode()
	print( "Template addon is loaded." )

	GameRules:SetHeroSelectionTime(30)
	GameRules:SetStartingGold(2000)--初始金钱
	GameRules:SetGoldPerTick( 0 )
	GameRules:SetCustomGameTeamMaxPlayers( DOTA_TEAM_GOODGUYS, 6 )
	GameRules:SetCustomGameTeamMaxPlayers( DOTA_TEAM_BADGUYS, 0 )
	GameRules:SetFirstBloodActive( false )						--是否产生第一滴血
  	GameRules:SetHideKillMessageHeaders( true )		
  	GameRules:SetStrategyTime(0)
	GameRules:SetShowcaseTime(0)
	GameRules:SetPreGameTime(0)
	GameRules:SetHeroRespawnEnabled( false )
	GameRules:GetGameModeEntity():SetFogOfWarDisabled(true)
	
	-- ListenToGameEvent("entity_killed", Dynamic_Wrap(Kekaishi,"OnEntityKilled"), self)
  	ListenToGameEvent( "game_rules_state_change", Dynamic_Wrap( Kekaishi, 'OnGameRulesStateChange' ), self )
  	ListenToGameEvent('player_chat', Dynamic_Wrap(Kekaishi, 'OnPlayerMessage'), self)
  	ListenToGameEvent('dota_player_pick_hero', Dynamic_Wrap(Kekaishi, 'OnPlayerPickHero'), self)
  	ListenToGameEvent("player_reconnected", Dynamic_Wrap(Kekaishi, 'OnPlayerReconnect'), self)
  	ListenToGameEvent('player_disconnect', Dynamic_Wrap(Kekaishi, 'OnDisconnect'), self)
  	-- ListenToGameEvent('dota_item_picked_up', Dynamic_Wrap(Kekaishi, 'OnItemPickedUp'), self)
  	local proto = {
  		"C2S_GET_PLAYER_DATA",
  		"C2S_PUSH_GOODS",
  		"C2S_POP_GOODS",
  		"C2S_COMPLETE_TRADE",
  		"C2S_REQUEST_TRADE",
  		"C2S_CANCLE_TRADE",
  		"C2S_PAIMAI",
  		"C2S_PAIMAI_END",
  		"C2S_PAIMAI_GIVEUP",
  		"C2S_DIYA",
  		"C2S_BUILD",
  		"C2S_SELL",
  		"C2S_GET_PM_DATA",
  		"C2S_GET_TRADING_DATA",
  		"C2S_REQUEST_PAIMAI",
  		"C2S_GET_CITY_DATA",
  		"C2S_GET_UNITNAME",
  		"C2S_GET_TURNTABLE",
  		"C2S_GIVEUPGAME",

  		-- "S2C_CHANGE_PLAYER",
  		-- "S2C_CHANGE_TIME",

  		"C2S_GET_ITEM_DATA",
  		"S2C_CHOICE_DONE",
  	}
  	for i,v in ipairs(proto) do
  		CustomGameEventManager:RegisterListener( v, function(...) return self[v](self, ... ) end )
  	end
  	
  	_G.DropTable = {}

  	self._eGameMode = GameRules:GetGameModeEntity()
  	self._eGameMode:SetCameraDistanceOverride(2000)
    self._eGameMode:SetLoseGoldOnDeath(false)
    -- self._eGameMode:SetItemAddedToInventoryFilter( Dynamic_Wrap( Kekaishi, "ItemAddedFilter" ), self )
    self._eGameMode:SetExecuteOrderFilter( Dynamic_Wrap( Kekaishi, "ExecuteOrderFilter" ), self )
    self._eGameMode:SetDamageFilter(Dynamic_Wrap( Kekaishi, "OnDamageFilter"), self)
	self._eGameMode:SetThink( "OnThink", self, "GlobalThink", 2 )

end


function Kekaishi:ForceAssignHeroes()
	for nPlayerID = 0, ( DOTA_MAX_TEAM_PLAYERS - 1 ) do
		local hPlayer = PlayerResource:GetPlayer( nPlayerID )
		if hPlayer then
			if not PlayerResource:HasSelectedHero( nPlayerID ) then
				hPlayer:MakeRandomHeroSelection()
			end
		end
	end
end

function Kekaishi:OnPlayerPickHero(event )
	local hero = EntIndexToHScript(event.heroindex)
	hero:SetAbsOrigin(Vector(0,0,0))
	hero:AddNewModifier(hero, nil, "modifier_medusa_stone_gaze_stone", {})
	hero.doubledice = 0
	local abc = hero:GetAbilityCount()
	for i=0,abc-1 do
		local ab = hero:GetAbilityByIndex(i)
		if ab then
			ab:SetLevel(1)
		end
	end
end
local distances = {
	curDistance,curDistance,curDistance,curDistance,curDistance,curDistance,curDistance
}
function Kekaishi:ModifyDistance( dis,playerId )
	dis = dis or 0
	newdis = distances[playerId+1] + dis
	local hPlayer = PlayerResource:GetPlayer(playerId)
	distances[playerId+1] = newdis
	CustomGameEventManager:Send_ServerToPlayer(hPlayer,"S2C_CAMERA_CHANGE",{ dis = newdis})
end
function Kekaishi:OnPlayerMessage( event )
	--PrintTable(event)
	local playerId = event.playerid
	local text = event.text
	local playerName = PlayerResource:GetPlayerName(playerId)
	local hero = PlayerResource:GetSelectedHeroEntity(playerId)
	if string.find(text,"-createunit") then
		local unitName = string.sub(text,13,string.len(text))
		local unit = CreateUnitByName(unitName, hero:GetAbsOrigin(), true, nil, nil, DOTA_TEAM_BADGUYS)
		unit:AddNewModifier(nil, nil, "modifier_phased", {duration=0.1}) 
		unit:SetControllableByPlayer(playerId, true)
	end
	
	-- local steamId = PlayerResource:GetSteamAccountID(playerId)

	-- if steamId=="135093847" or steamId==135093748 then
	-- 	local str = string.sub(text,1,5)
	-- 	if str=="-gold" then
	-- 		local goldstr = string.sub(text,7,string.len(text))
	-- 		local hero = PlayerResource:GetSelectedHeroEntity(playerId)
	-- 		local goldnum = tonumber(goldstr)
	-- 		if goldnum then
	-- 			ModifyGoldLtx(hero,goldnum)
	-- 		end
	-- 	end
	-- end
	if text == "hg" or text == "hc" then
		self:test_chat(hero,text,args)
		return
	elseif text == "++" then
		self:ModifyDistance(100,playerId)
		return 
	elseif text == "--" then
		self:ModifyDistance(-100,playerId)
		return
	end
	local emp = text:find(" ")
	if emp and text:sub(1,1)=='-' then
		local cmd = text:sub(2,emp-1)
		local args = text:sub(emp+1,#text)
		local steamid = PlayerResource:GetSteamAccountID(playerId)
		local isAdmin = ((steamid == 135093748) or (steamid == "135093748") )
		self:test_chat(hero,cmd,args,isAdmin)
	end
end
GameRules.playerlist = {}
--一些需要在游戏初始化完成之后才进行的初始化动作在这里进行
function Kekaishi:initGameData()
	local t = {}
	for nPlayerID = 0, ( DOTA_MAX_TEAM_PLAYERS - 1 ) do

		local hPlayer = PlayerResource:GetPlayer( nPlayerID )
		if hPlayer then
			table.insert(t,nPlayerID)
		end
	end
	--打乱table的顺序
	GameRules.playerlist = ShuffledList(t)
end

_G.bIsInited = false


-- Evaluate the state of the game
function Kekaishi:OnThink()
	if GameRules:State_Get() == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
		--print( "Template addon script is running." )
		local time = GameRules:GetGameTime()

		if time >= 22 and not _G.bIsInited then
			
		end
	elseif GameRules:State_Get() >= DOTA_GAMERULES_STATE_POST_GAME then
		
		return nil
	end
	return 1
end